package cn.edu.swu.miniwebsvr.core;

import cn.edu.swu.miniwebsvr.handler.DefaultHandler;
import cn.edu.swu.miniwebsvr.handler.EchoHandler;
import cn.edu.swu.miniwebsvr.handler.TimeHandler;
import java.util.HashMap;
import java.util.Map;

public class Config {
    private final int port = 8080;
    // 关键修改：替换为你的实际webroot绝对路径！
    private final String webRoot = "D:\\java\\workspace\\demo_1\\javaweb2025\\3-web-server\\webroot";
    private final Map<String, Handler> handlerMap = new HashMap<>();

    private Config() {
        handlerMap.put("/", new DefaultHandler());
        handlerMap.put("/time", new TimeHandler());
        handlerMap.put("/echo", new EchoHandler());
    }

    public static Config getInstance() {
        return Holder.INSTANCE;
    }

    private static class Holder {
        private static final Config INSTANCE = new Config();
    }

    public int getPort() {
        return port;
    }

    public String getWebRoot() {
        return webRoot;
    }

    public Handler getHandler(String url) {
        // TODO：【222024321072046/马云山]    精确匹配
        if (handlerMap.containsKey(url)) {
            return handlerMap.get(url);
        }

        // 路径前缀匹配
        String[] urlParts = url.split("/");
        for (int i = urlParts.length; i > 0; i--) {
            StringBuilder pathBuilder = new StringBuilder();
            for (int j = 0; j < i; j++) {
                if (!urlParts[j].isEmpty()) {
                    pathBuilder.append("/").append(urlParts[j]);
                }
            }
            String candidatePath = pathBuilder.length() == 0 ? "/" : pathBuilder.toString();
            if (handlerMap.containsKey(candidatePath)) {
                return handlerMap.get(candidatePath);
            }
        }

        // 无匹配时返回默认处理器
        return handlerMap.get("/");
    }
}